package com.fc.happyteam.shiro.realm;

import com.fc.happyteam.entity.SmsHistoryEntity;
import com.fc.happyteam.entity.UserEntity;
import com.fc.happyteam.service.ISmsHistoryService;
import com.fc.happyteam.service.IUserPermService;
import com.fc.happyteam.service.IUserRoleService;
import com.fc.happyteam.service.IUserService;
import com.fc.happyteam.utils.Constant;
import lombok.Getter;
import lombok.Setter;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.authz.permission.WildcardPermission;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

@Getter
@Setter
public class UserRealm extends AuthorizingRealm {
    private Logger logger =  LoggerFactory.getLogger(UserRealm.class);
    @Autowired
    private IUserService userService;

    @Autowired
    private IUserRoleService userRoleService;

    @Autowired
    private IUserPermService userPermService;

    @Autowired
    private ISmsHistoryService smsHistoryService;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String username = (String) authenticationToken.getPrincipal();
        MyAuthenticationToken myAuthToken = (MyAuthenticationToken) authenticationToken;
        String loginMethod = myAuthToken.getLoginMethod();

        // Null username is invalid
        if (username == null) {
            throw new AccountException("用户名不能为空！");
        }

        //查询用户信息
        UserEntity user = null;
        if(Constant.LoginMethod.PHONE_SMS_CODE.getValue().equals(loginMethod)){
            String smsCode = ((MyAuthenticationToken) authenticationToken).getSmsCode();

            SmsHistoryEntity sms = smsHistoryService.queryByMobileAndCode(username,smsCode);
            if(sms != null){
                user = userService.queryByMobile(sms.getPhone());
            }
        }else if(Constant.LoginMethod.PHONE_PASSWORD.getValue().equals(loginMethod)){
            user = userService.queryByMobile(username);
        }else {
            user = userService.queryByUserName(username);
        }

        //账号不存在
        if(user == null) {
            throw new UnknownAccountException("账户不存在");
        }

        //账号锁定
        if(user.getStatus() == 0){
            throw new LockedAccountException("该账号已经被锁定");
        }
        SimpleAuthenticationInfo authInfo = new SimpleAuthenticationInfo(user, user.getPassword(), getName());
        return authInfo;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        logger.info("doGetAuthorizationInfo+"+principals.toString());
        UserEntity user = (UserEntity)principals.getPrimaryPrincipal();
        //把principals放session中 key=userId value=principals
        SecurityUtils.getSubject().getSession().setAttribute(String.valueOf(user.getId()), SecurityUtils.getSubject().getPrincipals());

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //赋予角色
        info.setRoles(userRoleService.queryRoleSet(user.getId()));
        //info.setStringPermissions(userPermService.queryPermissionSet(user.getId()));
        //赋予权限
        Set<String> stringSet = userPermService.queryPermissionSet(user.getId());
        for(String ps: stringSet)
        {
            WildcardPermission wp = new WildcardPermission(ps,false);
            info.addObjectPermission(wp);
        }
        return  info;
    }
}
